package com.lin.videospringboot.controller;


import com.lin.videospringboot.Utils.ParseJson;
import com.lin.videospringboot.been.User;
import com.lin.videospringboot.config.ResourceHandler;
import com.lin.videospringboot.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/video/user")
public class UserController {
    @Autowired
    UserServiceImpl userService;

    @Autowired
    ResourceHandler resourceHandler;

    @Value("${upload.avatarSrc}")
    public void setAvatarSrc(String avatarSrc) {
        UserController.avatarSrc = avatarSrc;
    }

    static private String avatarSrc;


    @Value("${connector.pip}")
    public void setPip(String pip) {
        UserController.pip = pip;
    }

    static private String pip;

    @Value("${server.port}")
    public void setPport(String pport) {
        UserController.pport = pport;
    }

    static private String pport;


    @RequestMapping("/checkNameNum")
    @ResponseBody
    public int checkNameNum(@RequestBody String s) {
        Map<String,Object> mp = ParseJson.parseJson(s);
        String name = (String) mp.get("name");
        int userId = (int) mp.get("userId");
        return userService.countUserName(name,userId);
    }


    @RequestMapping("/updateInfo")
    @ResponseBody
    public int UpdateUserById(@RequestBody String s) {
        Map<String,Object> mp = ParseJson.parseJson(s);
        try {
            int userId = (int) mp.get("userId");
            User user = userService.queryUserById(userId);
            String name = (String) mp.get("name");
            String description = (String) mp.get("description");
            String sex = (String) mp.get("sex");
            int age = (int) mp.get("age");
            String email = (String) mp.get("email");
            user.setName(name);
            user.setDescription(description);
            user.setSex(sex);
            user.setAge(age);
            user.setEmail(email);
            return userService.updateUserById(user);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    @RequestMapping("/uploadAvatar")
    @ResponseBody
    public String uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId")String userId) {
        if (file.isEmpty()) return "上传失败，请选择文件";
//        \ 和 . 都是转义字符
        String url = avatarSrc + userId;
        String fileName =  userId + UUID.randomUUID().toString().replaceAll("-","") + "." + file.getOriginalFilename().split("\\.")[1];
        File dest = new File(url + "\\" + fileName);
        File dir = new File(url);
        if(!dir.exists() && !dir.isDirectory()) {
            dir.mkdir();
        }
        try {
            file.transferTo(dest);
//            修改数据库中对于的视频url
            String nurl = "http:\\\\" + pip + ":" + pport + "\\video\\user\\getAvatar\\" + userId + "\\" + fileName;
            userService.updateUserURL(nurl,new Integer(userId));
            return "上传成功";
        } catch (IOException e) {
            System.out.println("文件上传失败");
            return "上传失败";
        }
    }

    @RequestMapping("/getUserInfoById")
    @ResponseBody
    public User getUserInfoById(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            int userId = (int) mp.get("userId");
            User user = userService.queryUserById(userId);
            user.setPassword("");
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @RequestMapping("/getAvatar/{userId}/{fileName}")
    @ResponseBody
    @CrossOrigin
    public void getAvatar(@PathVariable("fileName")String fileName, @PathVariable("userId")String userId, HttpServletRequest request, HttpServletResponse response) {
        try {
            String path = avatarSrc + userId + "\\" + fileName;
            Path filePath = Paths.get(path);
            if (Files.exists(filePath)) {
                String mimeType = Files.probeContentType(filePath);
                if (!StringUtils.isEmpty(mimeType)) {
                    response.setContentType(mimeType);
                }
                request.setAttribute(ResourceHandler.FILE_ATTR, filePath);
                resourceHandler.handleRequest(request, response);
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            }
        }catch (Exception e) {
            System.out.println("获取用户头像失败");
            e.printStackTrace();
        }
    }
}
